package com.onesports.intelligent.k12.polarlight.security.wx;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.onesports.intelligent.k12.polarlight.cache.RedisTokenProvider;
import com.onesports.intelligent.k12.polarlight.common.utils.Result;
import com.onesports.intelligent.k12.polarlight.security.DomainUserDetails;
import com.onesports.intelligent.k12.polarlight.security.jwt.JwtTokenProvider;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author aj
 * 微信登录成功处理
 */

public class WxLoginSuccessHandler implements AuthenticationSuccessHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private final JwtTokenProvider jwtTokenProvider;

    private final RedisTokenProvider redisTokenProvider;

    public WxLoginSuccessHandler(JwtTokenProvider jwtTokenProvider,
                                 RedisTokenProvider redisTokenProvider) {
        this.jwtTokenProvider = jwtTokenProvider;
        this.redisTokenProvider = redisTokenProvider;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        Result result = new Result();
        String token;
        DomainUserDetails userDetails = (DomainUserDetails) authentication.getPrincipal();
        if (userDetails.isCoach()) {
            token = redisTokenProvider.createToken(authentication, RedisTokenProvider.TOKEN_PREFIX_COACH, false);
        } else {
            token = jwtTokenProvider.createToken(authentication, null, false);
        }
        LoginVO loginVO = LoginVO.builder()
                .accessToken(token)
                .nickname(userDetails.getNickname())
                .gender(userDetails.getGender())
                .phone(userDetails.getPhone())
                .avatar(userDetails.getAvatar())
                .isCoach(userDetails.isCoach())
                .build();
        result.setCode(Result.SUCCESS);
        result.setData(loginVO);
        ObjectMapper mapper = new ObjectMapper();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK);

        try {
            response.getWriter().append(mapper.writeValueAsString(result));
        } catch (IOException e) {
            throw new BadCredentialsException("Failed to decode basic authentication token");
        }
    }

    @Data
    @Builder
    public static class LoginVO {
        @ApiModelProperty(value = "访问令牌")
        private String accessToken;
        @ApiModelProperty(value = "用户名")
        private String nickname;
        @ApiModelProperty(value = "手机号")
        private String phone;
        @ApiModelProperty(value = "头像")
        private String avatar;
        @ApiModelProperty(value = "性别：1-男;2-女")
        private String gender;
        @ApiModelProperty(value = "是否教练")
        private Boolean isCoach;
    }

}
